/*
 *
 * Copyright 2006-2009 Matthieu Chase Heimer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
package com.macro10.xroads.xml;

import com.macro10.util.FileUtils;
import com.macro10.xroads.xml.generated.XMLMonster;
import com.macro10.xroads.xml.generated.XMLMonsterCollection;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;

public class MonsterParser {

    private static final Logger logger = Logger.getLogger(MonsterParser.class.getPackage().getName());
    private static String xmlDir = System.getProperty("MonsterDir", "src");
    private static String xmlFile = System.getProperty("MonsterFile", "monsters.xml");
    private static MonsterParser instance;
    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();
    private Map<Integer, XMLMonster> monsters;

    private MonsterParser() throws Exception {
        logger.log(Level.INFO, "Loaded " + getClass().getName());
        loadMonsters();
    }

    public static MonsterParser loadInstance() throws Exception {
        if (instance == null) {
            instance = new MonsterParser();
        }
        return instance;
    }

    public static MonsterParser getInstance() {
        return instance;
    }

    public void loadMonsters() throws Exception {
        w.lock();
        monsters = new HashMap<Integer, XMLMonster>();

        JAXBContext jc = null;
        Unmarshaller u = null;

        try {
            jc = JAXBContext.newInstance("com.macro10.xroads.xml.generated");
            u = jc.createUnmarshaller();
        } catch (JAXBException ex) {
            logger.log(Level.ERROR, "Error creating JAXB context for XMLMonsterParser", ex);
            w.unlock();
            throw ex;
        }

        logger.log(Level.INFO, "Searching for monster xml files underneath: " + new File(xmlDir).getAbsolutePath());
        File[] xmlFiles = FileUtils.getAllFilesUnderByName(new File(xmlDir), xmlFile);
        logger.log(Level.INFO, "Found " + xmlFiles.length + " monster xml file(s)");
        for (File monsterFile : xmlFiles) {
            logger.log(Level.INFO, "Parsing monster xml file: " + monsterFile.getName());
            try {
                XMLMonsterCollection monsterCollection = (XMLMonsterCollection) u.unmarshal(monsterFile);

                List<XMLMonster> monsterList = monsterCollection.getMonsters();
                for (XMLMonster monster : monsterList) {
                    Integer monsterId = monster.getMonsterId();
                    if (monsters.containsKey(monsterId)) {
                        logger.log(Level.WARN, "Replacing duplicate monster: " + monsterId);
                    }
                    monsters.put(monsterId, monster);
                }
            } catch (JAXBException ex) {
                logger.log(Level.ERROR, "Error parsing xml monster file: " + monsterFile.getName(), ex);
                w.unlock();
                throw ex;
            }
        }

        w.unlock();
    }

    public XMLMonster getMonster(int monsterId) {
        r.lock();
        XMLMonster monster = monsters.get(monsterId);
        r.unlock();
        return monster;
    }

    public Map<Integer, XMLMonster> getMonsters() {
        r.lock();
        Map<Integer, XMLMonster> localMonsters = this.monsters;
        r.unlock();
        return localMonsters;
    }
}
